#include "IDataBaseWorker.h"
#include <QDebug>
#include "ISqlite.h"
#include "IMysql.h"

IDataBaseWorker::IDataBaseWorker(QObject *parent)
    : QObject{parent}
{}
IDataBaseWorker::IDataBaseWorker(const SqlLinkParam &par, QObject *parent)
{
    setLinkParam(par);
}

void IDataBaseWorker::setLinkParam(const SqlLinkParam &par)
{
    if(par.sqlType == "QSQLITE"){
        mIIDb.reset(new ISqlite(par, this));
    } else if(par.sqlType == "QMYSQL"){
        mIIDb.reset(new IMysql(par, this));
    }
    mIIDb->init();
}

void IDataBaseWorker::refreshStatistics()
{

}


void IDataBaseWorker::setData(const QJsonObject &data)
{
    mIIDb->updateRow(data);
}

void IDataBaseWorker::onInit()
{

}

void IDataBaseWorker::onQuit()
{
    deleteLater();
}

void IDataBaseWorker::onLinkParamChanged(SqlLinkParam par)
{
    setLinkParam(par);
}

void IDataBaseWorker::onClearData()
{
    mIIDb->deleteRowByDateTime(mDateBegin, mDateEnd);
}

void IDataBaseWorker::onDateBeginChanged(QDateTime date)
{
    mDateBegin = date;
}

void IDataBaseWorker::onDateEndChanged(QDateTime date)
{
    mDateEnd = date;
}
QJsonObject IDataBaseWorker::getData(QString findText)
{
    QJsonArray objArray;
    QJsonObject obj;
    mIIDb->findRowsByData(findText, objArray);
    qDebug() << findText << obj << mIIDb->getErrMsg();
    if(obj.isEmpty()){
        obj.insert(DBCreatTime, QDateTime::currentDateTime().toString(DBDateTimeFormat));
        obj.insert(DBModifyTime, QDateTime::currentDateTime().toString(DBDateTimeFormat));
        obj.insert(DBUuid, mIIDb->getUuid());
        obj.insert(KeyData, QJsonObject());
        if(!mIIDb->createRow(obj)){
            qDebug() << mIIDb->getErrMsg();
        }
    } else {
        obj = objArray.at(0).toObject();
    }
    return obj;
}
void IDataBaseWorker::removeData(QString findText)
{
    QJsonObject obj = getData(findText);
    mIIDb->deleteRowByUuid(obj.value(DBUuid).toString());
}
QJsonObject IDataBaseWorker::getData(QDateTime dt)
{
    QJsonObject obj;
    mIIDb->findRowByDateTime(dt, obj);
    qDebug() << dt << obj << mIIDb->getErrMsg();
    if(obj.isEmpty()){
        obj.insert(DBCreatTime, dt.toString(DBDateTimeFormat));
        obj.insert(DBModifyTime, dt.toString(DBDateTimeFormat));
        obj.insert(DBUuid, mIIDb->getUuid());
        obj.insert(KeyData, QJsonObject());
        if(!mIIDb->createRow(obj)){
            qDebug() << mIIDb->getErrMsg();
        }
    }
    return obj;
}

void IDataBaseWorker::onDataChanged(QJsonObject data)
{
    QJsonObject todayData = getData(QDateTime::fromString(data.value(DBCreatTime).toString(), DBDateTimeFormat));
    todayData[DBModifyTime] = data.value(DBModifyTime);
    todayData[KeyData] = data;
    setData(todayData);
}
